package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * projectName: tingshu-parent
 *
 * @author: 比丢比丢
 * time: 2024/8/5 18:17 周一
 * description:
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;
    @Autowired
    private MinioClient minioClient;

    /**
     * 图片(封面,头像)文件上传
     * @param multipartFile
     * @return
     */
    @Override
    public String fileUpload(MultipartFile multipartFile) {
        //1.业务校验图片内容格式是否合法
        try {
            BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
            if (bufferedImage == null) {
                throw new GuiguException(400,"文件格式有误");
            }
            //2.业务校验图片大小合法
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width > 900 || height > 900) {
                throw new GuiguException(400,"文件大小有误");
            }
        } catch (IOException e) {
            throw new GuiguException(400,"文件格式有误");
        }
        try {
            //3.将文件上传到minio
            //3.1 生成带有文件夹目录文件名称 形式: /日期/随机文件名称.后缀
            String folder = "/" + DateUtil.today();
            String fileName = IdUtil.randomUUID();
            //获取文件后缀
            String extName = FileNameUtil.extName(multipartFile.getOriginalFilename());
            String objName = folder + "/" + fileName + "." + extName;
            //3.2 调用minio客户对象上传文件方法
            String bucketName = minioConstantProperties.getBucketName();
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objName).stream(
                    multipartFile.getInputStream(),multipartFile.getSize(),-1)
                    .contentType(multipartFile.getContentType())
                    .build());
            //3.3 拼接上传文件在线路径地址
            return minioConstantProperties.getEndpointUrl() + "/" + bucketName + objName;
        } catch (Exception e) {
            throw new GuiguException(500,"文件上传失败");
        }
    }
}
